import socket
import json
import random
import time
import gevent
from gevent import monkey
monkey.patch_all()

ADDRESS = ('127.0.0.1', 8712)
# 如果开多个客户端，这个client_type设置不同的值，比如客户端1为linxinfa，客户端2为linxinfa2
client_type = 'linxinfa'


def send_data(client, cmd, **kv):
    global client_type
    jd = {}
    jd['COMMAND'] = cmd
    jd['client_type'] = client_type
    jd['data'] = kv

    jsonstr = json.dumps(jd)
    print('send: ' + jsonstr)
    client.sendall(jsonstr.encode('utf8'))


def input_client_type():
    i = random.randint(1,10)
    name = "client" + str(i)
    return name

def main():
    client_type = input_client_type()
    client = socket.socket()
    client.connect(ADDRESS)
    print(client.recv(1024).decode(encoding='utf8'))
    send_data(client, 'CONNECT')
    while True:
        a = str(random.randint(100000000, 9999999999))
        send_data(client, 'SEND_DATA', data=a)
        time.sleep(random.randint(1, 5))


if '__main__' == __name__:
    a = []
    for i in range(1,5):
        a.append(gevent.spawn(main))
    gevent.joinall(a)
